import { Module } from 'vuex'
import { IRootState } from '../types'
import { IBaseState, ITabState } from './types'

const baseModule: Module<IBaseState, IRootState> = {
  namespaced: true,
  state() {
    return {
      tabs: [],
      activeTabName: '',
      newprojectDialogVisible: false
    }
  },
  getters: {
    getActiveTab: (state) => (index: number) => {
      return state.tabs[index]
    },
    getActiveTabName: (state) => {
      return state.activeTabName
    },
    getAllTabs: (state) => {
      return state.tabs
    }
  },
  mutations: {
    SET_ACTIVETAB(state, val: string) {
      state.activeTabName = val
    },
    ADD_NEW_TAB(state, val: ITabState) {
      state.tabs.push(val)
    },
    DELETE_TAB(state, val: number) {
      state.tabs.splice(val, 1)
    },
    SET_ACTIVETAB_ISMODIFY(state, val: any) {
      const index = state.tabs.findIndex((item) => item.title === val.title)
      if (index > -1) {
        // state.tabs[index]?.isModify = val.isModify
        //state.tabs[index].unsaved = true;
      }
    },
    SET_NEWPROJECT_DIALOG_VISIBLE(state, val: boolean) {
      state.newprojectDialogVisible = val
    }
  },
  actions: {
    openPage({ commit, state }, val: any) {
      let canPush = true
      const activeName = val.title
      state.tabs.forEach((item) => {
        if (item.title === val.title) {
          canPush = false
        }
      })
      if (canPush) {
        commit('ADD_NEW_TAB', val)
      }
      commit('SET_ACTIVETAB', activeName)
    },
    closePage({ commit, state }, deleteTabIndex: number) {
      const len = state.tabs.length
      let activeName = ''
      if (state.activeTabName === state.tabs[deleteTabIndex].title) {
        if (len > 1) {
          // 删除最后一个
          if (deleteTabIndex === len - 1) {
            activeName = state.tabs[deleteTabIndex - 1].title
          } else if (deleteTabIndex === 0) {
            // 删除第一个
            activeName = state.tabs[1].title
          } else {
            activeName = state.tabs[deleteTabIndex + 1].title
          }
        }
        commit('SET_ACTIVETAB', activeName)
      }
      commit('DELETE_TAB', deleteTabIndex)
    },
    closePagesByProject({ commit, state }, projectName: string) {
      let index = -1
      do {
        index = state.tabs.findIndex((item) => item.projectName === projectName)
        if (index > -1) {
          state.tabs.splice(index, 1)
        }
      } while (index !== -1)
    },
    closePagesByModule({ commit, state }, { projectName, projectModuleName }) {
      let index = -1
      do {
        index = state.tabs.findIndex(
          (item) =>
            item.projectName === projectName &&
            item.moduleName === projectModuleName
        )
        if (index > -1) {
          state.tabs.splice(index, 1)
        }
      } while (index !== -1)
    }
  }
}

export default baseModule
